package cn.bblocks.cacheTest.suport;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @program:
 * @author: captain.ma
 * @date: 2018-11-20
 * @since: 1.0.0.0
 */
public class GenericsUtils {
    @SuppressWarnings("rawtypes")
    public static Class getSuperClassGenricType(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if ((index >= params.length) || (index < 0)) {
            throw new RuntimeException("你输入的索引"
                    + (index < 0 ? "不能小于0" : "超出了参数的总数"));
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class) params[index];
    }

    @SuppressWarnings("rawtypes")
    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /*
     * If more than one interface may be the return type is not the type of
     * required
     */
    public static Class<?> getMethodParameterGenericsInterfaceType(Object req) {
        ParameterizedType parameterizedType = null;
        try {
            parameterizedType = (ParameterizedType) (req.getClass()
                    .getGenericInterfaces()[0]);
        } catch (Exception e) {
            return getSuperClassGenricType(req.getClass());
        }
        return (Class<?>) parameterizedType.getActualTypeArguments()[0];
    }


}
